package com.szt.sy.controller.api.open;

import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.szt.sy.controller.base.ApiBaseController;
import com.szt.sy.entity.blog.Article;
import com.szt.sy.service.blog.article.ArticleService;
import com.szt.sy.vo.rep.base.RepBaseVO;
import com.szt.sy.vo.rep.base.RepPageVO;

/***
 * 接口-开放-文章
 * 
 * @author wwy
 *
 */
@RestController
@RequestMapping("api/open/article")
public class ApiOpenArticleController extends ApiBaseController {
	
	@Autowired
	private ArticleService articleService;
	
	@PostMapping("page")
	public RepPageVO<List<Article>> articlePage(Integer currentPage, Integer pageSize, Short hot, String tag,
			String keyword) {
		RepPageVO<List<Article>> repVO = new RepPageVO<>();
		Page<Article> page = new Page<>(currentPage, pageSize);
		EntityWrapper<Article> wrapper = new EntityWrapper<>();
		wrapper.orderBy("id", false);
		if (StringUtils.isNotBlank(tag)) {
			String[] tags = tag.split(",");
			for (String s : tags) {
				wrapper.or("find_in_set({0},tags)", s);
			}
			
			// wrapper.where("find_in_set({0},tags)", tag.split(",")[0]);
		}
		if (StringUtils.isNotBlank(keyword)) {
			wrapper.like("title", keyword);
		}
		if (hot != null) {
			wrapper.eq("hot", hot);
		}
		
		Page<Article> pageInfo = articleService.selectPage(page, wrapper);
		List<Article> data = pageInfo.getRecords();
		data = data.stream().peek(article -> article.setContent("")).collect(Collectors.toList());
		repVO.setCommonSuccess();
		repVO.setData(data);
		repVO.setCurrentPage(pageInfo.getCurrent());
		repVO.setTotalPage(pageInfo.getPages());
		repVO.setTotalResult(page.getTotal());
		return repVO;
	}
	
	@PostMapping("detail")
	public RepBaseVO<Article> articleDetail(Long id) {
		RepBaseVO<Article> repVO = new RepBaseVO<>();
		Article article = articleService.selectById(id);
		articleService.increaseViews(id);
		return repVO.setCommonSuccess().setData(article);
	}
}
